/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

package com.colony.transport;

import com.argot.network.TypeEndPoint;
import com.argot.network.TypeLink;
import com.colony.concurrent.ThreadActivator;

public abstract class Server
{
	private TypeLink _back;
	private ThreadActivator _pool;
	
	public Server( TypeLink back, ThreadActivator workerPool )
	{
		_back = back;
		_pool = workerPool;
	}

	public Server( ThreadActivator workerPool )
	{
		this(null,workerPool);
	}
	
	public TypeLink getTypeLink()
	{
		return _back;
	}
	
	public void setTypeLink( TypeLink link )
	{
		_back = link;
	}
	
	public ThreadActivator getPool()
	{
		return _pool;
	}

	protected boolean assignServerThread( TypeEndPoint request )
	{
		return _pool.assignThread( new ServerWorker( request ) );
	}
	
	protected void processMessage( TypeEndPoint request )
	{
		try
		{
			while (true) 
			{
				int magic1 = request.getInputStream().read();
				int magic2 = request.getInputStream().read();
				if (magic1 == 10 && magic2 == 20 )
				{
					_back.processMessage(request);		
				}
				else
				{
					break;
				}
			}
		}
		catch( Throwable t )
		{
			t.printStackTrace();
		}
		finally
		{
			processFinish( request );
		}
	}
	
	private class ServerWorker
	implements Runnable
	{
		private TypeEndPoint _request;
		
		public ServerWorker( TypeEndPoint request )
		{
			_request = request;
		}
		
		public void run()
		{
			processMessage( _request );
		}
	}
	
	protected abstract void processFinish( TypeEndPoint request );
}
